package cn.javaee.springmvc.service;
import org.apache.ibatis.session.SqlSession;

import cn.javaee.springmvc.model.Address;
import cn.javaee.springmvc.model.Login;
import cn.javaee.springmvc.model.User;


public class UserDaoImpl implements UserDao {
//	  @Autowired
//	  DataSource datasource;
//	  @Autowired
//	  JdbcTemplate jdbcTemplate;
//	  public int register(User user) {
//		  String sql = "insert into users values(?,?,?,?,?,?,?)";
//		  return   jdbcTemplate.update(sql, new Object[] { user.getUsername(), user.getPassword(), user.getFirstname(),
//		  user.getLastname(), user.getEmail(), user.getAddress(), user.getPhone() });
//    }
//	    public User validateUser(Login login) {
//	    String sql = "select * from users where username='" + login.getUsername() + 
//	    		"' and password='" + login.getPassword()+ "'";
//	    List<User> users = jdbcTemplate.query(sql, new UserMapper());
//	    return users.size() > 0 ? users.get(0) : null;
//	    }
//  }
//	  class UserMapper implements RowMapper<User> {
//	  public User mapRow(ResultSet rs, int arg1) throws SQLException {
//	    User user = new User();
//	    user.setUsername(rs.getString("username"));
//	    user.setPassword(rs.getString("password"));
//	    user.setFirstname(rs.getString("firstname"));
//	    user.setLastname(rs.getString("lastname"));
//	    user.setEmail(rs.getString("email"));
//	    user.setAddress(rs.getString("address"));
//	    user.setPhone(rs.getInt("phone"));
//	    return user;
//	  }
	  

		public int registerUser(User user) {
			SqlSession sqlsession=MybatisSqlSessionFactory.getSqlSessionFactory().openSession();
			int i = 0;
			try {
			UserDao userdao=sqlsession.getMapper(UserDao.class);
			 i=  userdao.registerUser(user);
			sqlsession.commit();
			}finally {
				sqlsession.close();
			}
			return i;
		}
		
		public int registerAddress(User user, Address address) {
			SqlSession sqlsession=MybatisSqlSessionFactory.getSqlSessionFactory().openSession();
			int i = 0;
			try {
			UserDao userdao=sqlsession.getMapper(UserDao.class);
			 i=  userdao.registerAddress(user,address);
			sqlsession.commit();
			}finally {
				sqlsession.close();
			}
			return i;
		}

		public User validateUser(Login login) {
			SqlSession sqlsession=MybatisSqlSessionFactory.getSqlSessionFactory().openSession();
			try {
				UserDao userdao=sqlsession.getMapper(UserDao.class);
				return userdao.validateUser(login);
			}finally {
				sqlsession.close();
			}
		}

	}
